package com.example.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

/**
 * 数据库初始化工具类
 * 用于执行SQLite数据库初始化脚本
 */
public class DatabaseInitializer {
    
    /**
     * 初始化数据库表结构和基础数据
     */
    public static void initializeDatabase() {
        try {
            // 读取SQL脚本内容
            String sqlScript = readSqlScript();
            
            // 执行SQL脚本
            executeSqlScript(sqlScript);
            
            System.out.println("数据库初始化完成！");
            
        } catch (Exception e) {
            System.err.println("数据库初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 读取SQL脚本文件内容
     */
    private static String readSqlScript() throws IOException {
        StringBuilder sql = new StringBuilder();
        
        // 尝试从classpath读取
        try (InputStream is = DatabaseInitializer.class.getClassLoader()
                .getResourceAsStream("database_init_sqlite.sql")) {
            
            if (is != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        // 跳过注释行
                        if (!line.trim().startsWith("--") && !line.trim().isEmpty()) {
                            sql.append(line).append("\n");
                        }
                    }
                }
            } else {
                // 如果classpath中没有，尝试从项目根目录读取
                try (BufferedReader reader = new BufferedReader(
                        new FileReader("database_init_sqlite.sql"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (!line.trim().startsWith("--") && !line.trim().isEmpty()) {
                            sql.append(line).append("\n");
                        }
                    }
                }
            }
        }
        
        return sql.toString();
    }
    
    /**
     * 执行SQL脚本
     */
    private static void executeSqlScript(String sqlScript) throws SQLException {
        try (Connection conn = DatabaseUtil.getConnection();
             Statement stmt = conn.createStatement()) {
            
            // 分割SQL语句（以分号为分隔符）
            String[] sqlStatements = sqlScript.split(";");
            
            for (String sql : sqlStatements) {
                sql = sql.trim();
                if (!sql.isEmpty()) {
                    try {
                        stmt.execute(sql);
                        System.out.println("执行SQL: " + sql.substring(0, Math.min(50, sql.length())) + "...");
                    } catch (SQLException e) {
                        System.err.println("执行SQL失败: " + sql);
                        System.err.println("错误: " + e.getMessage());
                        // 继续执行其他SQL语句
                    }
                }
            }
        }
    }
    
    /**
     * 检查数据库是否已初始化
     */
    public static boolean isDatabaseInitialized() {
        try (Connection conn = DatabaseUtil.getConnection()) {
            // 检查是否存在users表
            return conn.getMetaData().getTables(null, null, "users", null).next();
        } catch (SQLException e) {
            return false;
        }
    }
    
    /**
     * 主方法，用于独立运行数据库初始化
     */
    public static void main(String[] args) {
        initializeDatabase();
    }
} 